<?php
Class Controller_Product_Counter extends Controller_Abstract
{
	function actionNumberCreate()
	{
		$this->_view['title'] = '编号生成';
		$product_categories = Product_Categories::getCategoriesTree();
		$this->_view['product_categories'] = json_encode($product_categories);
	}
	
	function actionNumberCreateSave()
	{
		$this->_view['title'] = '编号生成（保存）';
		if ($this->_context->isPOST())
		{
			$number = Product_Counter::numberCreate($_POST['quantity'], $_POST['product_categories_id']);
			if ($number['ack'] == SUCCESS)
			{
				$result = Product_Basic::createMulti($number['start_number'], $number['end_number'], $number['number_length'], $_POST['product_categories_id'], $_POST['weight']);
				$warehouse_id = Warehouse::getDefaultWarehouseId();
				if (isset($result['product_basic']))
				{
					foreach ($result['product_basic'] as $p)
					{
						Product_Warehouse::create($p['number'], $warehouse_id);
					}
				}
				if ($result['ack'] == FAILURE)
				{
					return $this->_redirectMessage('批量失败', '开始编号大于最后编号', url('Product::Counter/NumberCreate'), $result['ack']);
				}
				if ($result['ack'] == PARTIAL_FAILURE)
				{
					return $this->_redirectMessage('批量失败', $result['message'], url('Product::Counter/NumberCreate'), $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('批量成功', '正在返回..', url('Product::Counter/NumberCreate'), $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('编号失败', $number['message'], url('Product::Counter/NumberCreate'), $number['ack']);
			}
		}
		else
		{
			return $this->_redirect(url('Product::Counter/NumberCreate'));
		}
	}
	
	function actionHistoryList()
	{
		$this->_view['title'] = '历史查看';
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 20;
		$url_arr = Helper_BSS_Normal::buildCondition();
		$product_categories = Product_Categories::getCategoriesTree();
		$this->_view['product_categories'] = json_encode($product_categories);
		$user = Purchase_Order::getUser();
		$this->_view['user'] = $user['data'];
		$url_arr['limit'] = $user['ack'];
		$result = Product_Counter::search($url_arr, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$counter = $result['data'];
			foreach ($counter as &$c)
			{
				$c['categories_full_info'] = Product_Categories::getAncestorById($c['product_categories_id']);
				
				(Helper_Plu_Number::$status)?$c['number_prefix'] = Helper_Plu_Number::getNumberPrefixByCategoryId($c['product_categories_id']):'';
			}
			unset($c);
			$this->_view['counter'] = $counter;
			$page = new Helper_BSS_Page($result['pagination'], url('Product::Counter/HistoryList'));
			$this->_view['page'] = $page->getPage();
			unset($url_arr['limit']);
			$where = Product_Counter::buildSearchWhere($url_arr);
			$this->_view['total_quantity'] = QDB::getConn()->execute('select sum(product_counter.quantity) from product_counter where ' . $where)->fetchOne(); 
		}
	}
}